<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat with AI</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        #chat-container {
            display: flex;
        }
        #chat-box {
            width: 60%;
            height: 500px;
            border: 1px solid #ccc;
            padding: 10px;
            overflow-y: auto;
            margin-right: 10px;
        }
        #history-controls {
            width: 35%;
            border: 1px solid #ccc;
            padding: 10px;
        }
        #history-list {
            height: 300px;
            overflow-y: auto;
            margin-top: 10px;
            border-top: 1px solid #ccc;
            padding-top: 10px;
        }
        .history-item {
            cursor: pointer;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        .history-item:hover {
            background-color: #f9f9f9;
        }
        #user-input {
            width: 100%;
            padding: 5px;
            margin-top: 10px;
        }
        #send-btn {
            padding: 5px 10px;
            margin-top: 10px;
        }
        .control-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        .slider-container {
            display: flex;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <h1>Chat with AI</h1>
    <div class="slider-container">
        <label for="api-address"> 选择 API 地址:</label>
        <select id="api-address">
            <option value="ollama">Ollama</option>
            <option value="lmstudio">LM Studio</option>
            <option value="thuds">THUDS</option>
            <option value="zhipuai">ZhipuAI</option>
            <option value="deepseek">DeepSeek</option>
        </select>
    </div>
    <div class="slider-container">
        <label for="model-select"> 选择模型:</label>
        <select id="model-select">
            <option value="qwen2.5:3b">阿里通义千问 qwen2.5:3b</option>
            <option value="deepseek-r1:1.5b">深度搜索 deepseek-r1:1.5b</option>
            <option value="llama3.2">元宇宙 meta:llama3.2</option>
            <option value="mistral:7b-instruct-q2_k">法国强风 mistral:7b-q2_k</option>
            <option value="glm4">智谱清言 glm-4:9b-q4_k</option>
            <option value="phi">微软 microsoft:phi</option>
            <option value="phi3">微软 microsoft:phi3</option>
        </select>
    </div>
    <div class="slider-container">
        <label for="temperature"> 设置模型温度(严谨:0-1:灵活):</label>
        <input type="range" id="temperature" min="0" max="1" step="0.05" value="0.7">
        <span id="temperature-value">0.7</span>
    </div>
    <div id="chat-container">
        <!-- 左侧：当前对话 -->
        <div id="chat-box"></div>
        <!-- 右侧：历史对话控制区和列表 -->
        <div id="history-controls">
            <div class="control-buttons">
                <button id="new-btn">新建</button>
                <button id="export-btn">导出</button>
                <button id="export-all-btn">全部导出</button>
                <button id="clear-btn">清空</button>
            </div>
            <div id="history-list"></div>
        </div>
    </div>
    <input type="text" id="user-input" placeholder="输入你的问题...">
    <button id="send-btn">发送消息</button>

    <script>
        let messages = [];  // 存储当前对话上下文
        let currentSessionId = null;  // 当前会话 ID

        // 加载历史会话列表
        const loadHistory = async () => {
            const response = await fetch('/load_sessions');
            const data = await response.json();
            const historyList = document.getElementById('history-list');
            historyList.innerHTML = '';
            data.sessions.forEach(session => {
                const item = document.createElement('div');
                item.className = 'history-item';
                item.textContent = `${session.topic} (${session.created_at})`;
                item.addEventListener('click', () => loadSession(session.session_id));
                historyList.appendChild(item);
            });
        };

        // 加载指定会话
        const loadSession = async (sessionId) => {
            const response = await fetch(`/load_session?session_id=${sessionId}`);
            const data = await response.json();
            messages = data.messages;
            currentSessionId = sessionId;
            updateChatBox();
        };

        // 更新聊天窗口
        const updateChatBox = () => {
            const chatBox = document.getElementById('chat-box');
            chatBox.innerHTML = '';
            messages.forEach(message => {
                chatBox.innerHTML += `<p><strong>${message.role}:</strong> ${message.content}</p>`;
            });
        };

        // 发送消息
        const sendMessage = async () => {
            const userInput = document.getElementById('user-input').value;
            if (!userInput) return;

            // 如果是新会话，生成会话 ID
            if (!currentSessionId) {
                currentSessionId = new Date().toISOString();
            }

            // 添加用户消息
            messages.push({ role: 'user', content: user_input });
            updateChatBox();
            document.getElementById('user-input').value = '';

            // 获取温度值、模型名称和 API 地址
            const temperature = parseFloat(document.getElementById('temperature').value);
            const modelName = document.getElementById('model-select').value;
            const apiAddress = document.getElementById('api-address').value;

            // 发送请求到服务器
            const response = await fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ 
                    session_id: currentSessionId,
                    message: userInput,
                    messages: messages,
                    temperature: temperature,
                    model_name: modelName,
                    api_address: apiAddress
                }),
            });

            const data = await response.json();
            messages = data.messages;
            updateChatBox();
        };

        // 绑定发送按钮
        document.getElementById('send-btn').addEventListener('click', sendMessage);

        // 绑定回车键
        document.getElementById('user-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 初始化加载历史会话
        loadHistory();
    </script>
</body>
</html>